package xq.gwt.mvc.model;

public class DoublePropertyModel extends AbstractPropertyModel {
	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -3206213233369562042L;
	private Double value;

	public Double getValue() {
		return value;
	}

	public void setValue(Double value) {
		Double oldValue = this.value;
		this.value = value;
		setHasError(false);
		notifyPropertyChanged(oldValue, value);
	}

	@Override
	public String getText() {
		if(getValue() == null)
			return null;
		return String.valueOf(getValue());
	}

	@Override
	public void setText(String text) throws ConversionException {
		setHasError(false);
		if((text == null) ||(text.equals(""))){
			setValue(null);
			return;
		}
		Double doubleVal;
		try {
			doubleVal = Double.parseDouble(text);
		} catch (Exception e) {
			//Prepare exception
			ConversionException ce = new ConversionException(e.getLocalizedMessage());
			ce.initCause(e);			
			//Try parse as integer
			try {
				Integer intVal = Integer.parseInt(text);
				doubleVal = new Double(intVal);
			} catch (Exception ex) {
				setHasError(true);
				throw ce;
			}			
		}
		
		setValue(doubleVal);
		
	}
	
	public Object getObjectValue() {		
		return getValue();
	}
	
	public Class getPropertyType() {		
		return Double.class;
	}

}
